package cn.jinjimi.app.poster.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baiiu.filter.util.UIUtil;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.framework.helper.annotation.EventTraceSelector;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.Source;
import cn.jinjimi.app.entity.AllPosterInfo;
import cn.jinjimi.app.managers.PosterCacheManager;
import cn.jinjimi.app.poster.PosterAdapter;
import cn.jinjimi.app.poster.bean.PosterInfo;
import cn.jinjimi.app.poster.interfaces.IPosterLoadMore;
import cn.jinjimi.app.poster.interfaces.PosterFragmentView;
import cn.jinjimi.app.poster.presenter.PosterPresenter;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.dialog.SharePosterDialog;
import cn.jinjimi.app.main.extend.BaseNetControlFragment;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lforxeverc on 16/9/23.
 */

public class PosterFragment extends BaseNetControlFragment implements PosterFragmentView, IPosterLoadMore, XRecyclerView.LoadingListener, PosterAdapter.PosterListener {
    private int position;
    XRecyclerView recyclerView;
    PosterAdapter mAdapter;
    PosterPresenter mPresenter;
    TextView tvName;
    String title = "";
    String productId;
    String productName;
    SharePosterDialog dialog;
    Map<Integer, List<PosterInfo>> mPosterCache = new HashMap<>();
    int loadType = PosterContainerFragment.LoadType.LOAD_WAIT;
    int categoryCode, subCategoryCode;
    int mCurrentPage = PosterPresenter.DEFAULT_PAGE;
    int mTotal;
    boolean onlyShowCache = false;
    public static final int COLUMN_POSTER = 3;
    public static final int COLUMN_JINJU = 2;
    int columnNum = COLUMN_POSTER;

    public void setPosition(int position) {
        this.position = position;
    }

    public void setLoadType(int loadType) {
        this.loadType = loadType;
    }

    @Override
    protected int getBizLayoutResourceId() {
        return R.layout.fragment_poster_list;
    }

    @Override
    protected void initialBiz() {
        mPresenter = new PosterPresenter(this, categoryCode, subCategoryCode, productId);
        recyclerView = (XRecyclerView) findView().findViewById(R.id.gv_posters);
        tvName = (TextView) findView().findViewById(R.id.tv_name);
        if (categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER) {
            findView().findViewById(R.id.v_divider).setVisibility(View.VISIBLE);
            tvName.setText("产品：" + productName);
        } else {
            tvName.setVisibility(View.GONE);
        }
        if (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER) {
            recyclerView.setPadding(UIUtil.dp(getContext(), 6), 0, UIUtil.dp(getContext(), 6), 0);
        } else {
            recyclerView.setPadding(UIUtil.dp(getContext(), 13), 0, UIUtil.dp(getContext(), 13), 0);
        }
        columnNum = categoryCode == PosterContainerFragment.DataType.JINJU_POSTER ? COLUMN_JINJU : COLUMN_POSTER;
        GridLayoutManager glm = new GridLayoutManager(getContext(), columnNum);
        recyclerView.setLayoutManager(glm);
        recyclerView.setPullRefreshEnabled(true);
        recyclerView.setLoadingMoreEnabled(true);
        recyclerView.setLoadingListener(this);
        recyclerView.setShowFooterWhenNoMore(false);
        mAdapter = new PosterAdapter(getActivity(), categoryCode);
        mAdapter.setListener(this);
        recyclerView.setAdapter(mAdapter);

    }


    @Override
    protected void loadData() {
        if (loadType == PosterContainerFragment.LoadType.LOAD_WAIT) {

        } else if (loadType == PosterContainerFragment.LoadType.LOAD_CACHE || loadType == PosterContainerFragment.LoadType.LOAD_CACHE_NET) {
            AllPosterInfo infos = PosterCacheManager.getInstance().getPosterListBy(categoryCode, subCategoryCode, title, productId);
            infos = infos == null ? AllPosterInfo.EMPTYSET : infos;
            onlyShowCache = true;
            infos.total = infos.posters.size();
            loadSuccess(PosterPresenter.DEFAULT_PAGE, infos, true);
            if (loadType == PosterContainerFragment.LoadType.LOAD_CACHE_NET) {
                mPresenter.loadAtPage(PosterPresenter.DEFAULT_PAGE);
            }
        } else if (loadType == PosterContainerFragment.LoadType.LOAD_NET) {
            mPresenter.loadAtPage(PosterPresenter.DEFAULT_PAGE);
        }

    }

    //
    public static PosterFragment create(int loadType, String title, int categoryCode, int subCategoryCode, String productId, String productName) {
        PosterFragment p = new PosterFragment();
        p.setLoadType(loadType);
        p.setTitle(title);
        p.setCategoryCode(categoryCode);
        p.setSubCategoryCode(subCategoryCode);
        p.setProductId(productId);
        p.setProductName(productName);
        return p;
    }

    @Override
    public String getTitle() {
        return title;
    }

    private void setTitle(String type) {
        title = type;
    }

    public void setCategoryCode(int categoryCode) {
        this.categoryCode = categoryCode;
    }

    public void setSubCategoryCode(int subCategoryCode) {
        this.subCategoryCode = subCategoryCode;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    @Override
    public void loadFail(int page, String msg) {
        recyclerView.loadMoreComplete();
        recyclerView.refreshComplete();

        if (page == PosterPresenter.DEFAULT_PAGE && (mAdapter == null || mAdapter.getItemCount() == 0)) {

            netLoadFaiEmpty();
        }
        ToastUtils.toastMessage(getContext(), msg);
        notifyDialogWithState(page, false);
    }

    @Override
    public void loadSuccess(int page, final AllPosterInfo data, boolean noMore) {
        recyclerView.loadMoreComplete();
        recyclerView.refreshComplete();
        netLoadSucc();
        mCurrentPage = page;
        if (page == PosterPresenter.DEFAULT_PAGE) {
            recyclerView.setRefreshTime(System.currentTimeMillis());
            mPosterCache.clear();
            mAdapter.clearItems();
            //商品海报当缓存数据和获取数据都为空时显示无商品海报view
            if (data == null || data.posters == null || data.posters.isEmpty()) {
                if (categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER) {
                    findView().findViewById(R.id.tv_no_poster).setVisibility(View.VISIBLE);
                } else if (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER) {
                    findView().findViewById(R.id.tv_no_jinju).setVisibility(View.VISIBLE);
                }
            } else {
                if (categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER) {
                    findView().findViewById(R.id.tv_no_poster).setVisibility(View.GONE);
                } else if (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER) {
                    findView().findViewById(R.id.tv_no_jinju).setVisibility(View.GONE);
                }

            }
            mTotal = data.total;
        }
        //手动添加海报productId（统计需要）
        if (data.posters != null && !data.posters.isEmpty()) {
            if (!StringUtils.isEmpty(productId))
                for (PosterInfo temp : data.posters) {
                    temp.productId = productId;
                }
            if (onlyShowCache) {
                sortCacheData(data);
            } else {
                mPosterCache.put(mCurrentPage, data.posters);
            }
            mAdapter.addItems(data.posters);
            notifyDialogWithState(page, true);
        } else {
            notifyDialogWithState(page, false);
        }
        initFooter(noMore);
    }


    private void sortCacheData(AllPosterInfo data) {
        int size = data.posters.size();
        int pages = size % PosterPresenter.LIMIT == 0 ? (size / PosterPresenter.LIMIT) : (size / PosterPresenter.LIMIT + 1);
        int length = PosterPresenter.LIMIT;
        for (int i = 0; i < pages; i++) {
            int offSet = length * i;
            int end = offSet + length - 1;
            List<PosterInfo> pageInfo;
            if (end > size - 1) {
                pageInfo = data.posters.subList(offSet, size);
            } else {
                pageInfo = data.posters.subList(offSet, offSet + length);
            }
            mPosterCache.put(i + 1, pageInfo);
        }
    }

    @Override
    public void updatePostInfo(PosterInfo info, int position) {
        updatePosterInfoMap(info, position);
    }

    private void initFooter(final boolean noMore) {
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                int measuredHeight = recyclerView.getHeight();
                View child = recyclerView.getChildAt(1);
                int cellHeight = 0;
                int marginTop = 0, marginBottom = 0;
                if (child != null) {
                    cellHeight = child.getHeight();
                    try {
                        marginBottom = ((ViewGroup.MarginLayoutParams) child.getLayoutParams()).bottomMargin;
                        marginTop = ((ViewGroup.MarginLayoutParams) child.getLayoutParams()).topMargin;
                    } catch (Exception e) {

                    }
                    cellHeight = cellHeight + marginBottom + marginTop;
                }
                int counts = mAdapter.getItemCount();
                int row = 0;
                if (counts % columnNum == 0) {
                    row = counts / columnNum;
                } else {
                    row = counts / columnNum + 1;
                }
                int allHeight = row * cellHeight;
                if (allHeight > measuredHeight && !onlyShowCache) {
                    recyclerView.setShowFooterWhenNoMore(true);
                } else {
                    recyclerView.setShowFooterWhenNoMore(false);
                }
                recyclerView.setNoMore(noMore);
                onlyShowCache = false;
            }
        }, 100);
    }


    @Override
    public void onRefresh() {
        mPresenter.loadAtPage(PosterPresenter.DEFAULT_PAGE);

    }

    @Override
    public void onLoadMore() {
        int page = mCurrentPage + 1;
        List<PosterInfo> mInfo = mPosterCache.get(page);
        if (mInfo != null) {
            loadSuccess(page, new AllPosterInfo(mInfo, mTotal), true);
        } else {
            mPresenter.loadAtPage(page);
        }
    }

    @Override
    public void onPosterItemClick(int position, PosterInfo info) {
        if (AccountManager.getInstance().isLogin()) {
            dialog = new SharePosterDialog();
            dialog.setContext(getActivity());
            dialog.setListener(this);
            dialog.setInfos(position, mTotal);
            dialog.setCategoryCode(categoryCode);
            if (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER) {
                dialog.setSource(Source.APP_READER_QUOTELIST);
            }
            getChildFragmentManager().beginTransaction().add(dialog, "").commitAllowingStateLoss();

            analyseWhenLogin(position, String.valueOf(info.templateId), categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER ? 0 : (categoryCode == PosterContainerFragment.DataType.INFORMATION_POSTER ? 1 : 2));

        } else {
            analyseWhenLogout(position, String.valueOf(info.templateId), categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER ? EventID.FROM_POSTER_PRODUCT : (categoryCode == PosterContainerFragment.DataType.INFORMATION_POSTER ? EventID.FROM_POSTER_INFORMATION : EventID.FROM_POSTER_QUOTES));

            Router.doLogin(getActivity());
        }
    }

    @EventTrace(EventID.APP_POSTER_LOGIN)
    private void analyseWhenLogout(@EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position, @EventTraceParam(EventDataField.ParamId) String templateId,
                                   @EventTraceParam(EventDataField.ParamFrom) String from) {
        LoginActivity.setLoginFrom(from);
    }

    private void analyseWhenLogin(@EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position, @EventTraceParam(EventDataField.ParamId) String templateId,
                                  @EventTraceSelector @EventTraceParam(value = EventDataField.ParamFrom, selector = {EventID.FROM_POSTER_PRODUCT, EventID.FROM_POSTER_INFORMATION, EventID.FROM_POSTER_QUOTES}) int categoryCodePosition) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null && mAdapter.getItemCount() > 0) {
            AllPosterInfo infos = new AllPosterInfo(mAdapter.getItems(), mTotal);
            PosterCacheManager.getInstance().savePosterList(categoryCode, subCategoryCode, title, productId, infos);
        }
    }

    int lastPosition = -1;

    @Override
    public void reqLoadPage(int page) {
        mPresenter.loadAtPage(page);
    }

    @Override
    public PosterInfo fetchPosterInfoWithPosition(int position) {
        lastPosition = position;
        PosterInfo info = getInfoWithPosition(position);
        return info;
    }


    private void notifyDialogWithState(int page, boolean success) {
        if (dialog != null && dialog.getDialog() != null && dialog.getDialog().isShowing() && isWithinPage(page)) {
            if (success) {
                dialog.onLoadPositionDataSuccess(lastPosition, getInfoWithPosition(lastPosition), false);
            } else {
                dialog.onLoadPositionDataFail(lastPosition);
            }
        }
    }

    private boolean isWithinPage(int page) {
        int start = (page - 1) * PosterPresenter.LIMIT;
        int end = page * PosterPresenter.LIMIT;
        return start <= lastPosition && lastPosition < end;
    }

    private PosterInfo getInfoWithPosition(int position) {
        int page = position / PosterPresenter.LIMIT + 1;
        int realPosition = position % PosterPresenter.LIMIT;
        List<PosterInfo> list = mPosterCache.get(page);
        if (list != null && list.size() > realPosition) {
            return list.get(realPosition);
        } else {
            return null;
        }
    }

    private void updatePosterInfoMap(PosterInfo info, int position) {
        int page = position / PosterPresenter.LIMIT + 1;
        int realPosition = position % PosterPresenter.LIMIT;
        List<PosterInfo> list = mPosterCache.get(page);
        if (list != null && list.size() > realPosition) {
            list.set(realPosition, info);
            mPosterCache.put(page, list);
        }
    }
}
